package com.ibbi.admin.client.front.category;

import java.util.ArrayList;
import java.util.List;

import com.ibbi.admin.client.rpc.obj.Category;

import corelib.client.CollectionUtil;
import corelib.client.linq.Linq;
import corelib.client.linq.Predicate;
import corelib.client.ui.widget.tree.SimpleTreeNode;

public class CategoryTreeUtil {
	
	public static SimpleTreeNode convert(List<Category> catalogs) {
		Category info = Linq.single(catalogs, new Predicate<Category>(){
			@Override
			public boolean apply(Category element) {
				return element.getLevel() == 0;
			}
		});
		
		CategoryTreeNode root = new CategoryTreeNode(info);
		root.setChildren(findChildren(root.getCategory().getId(), catalogs));
		return root;
	}
	
	private static List<SimpleTreeNode> findChildren(final int catId, List<Category> catalogs){
		List<Category> cats =  Linq.select(catalogs, new Predicate<Category>(){
			@Override
			public boolean apply(Category element) {
				return element.getPID() == catId;
			}
		});
		
		if (CollectionUtil.isEmpty(cats)) {
			return new ArrayList<SimpleTreeNode>();
		}
		
		List<SimpleTreeNode> treeNodes = new ArrayList<SimpleTreeNode>();
		for (Category productCatalogInfo : cats) {
			 CategoryTreeNode node = new CategoryTreeNode(productCatalogInfo);
			 node.setChildren(findChildren(productCatalogInfo.getId(), catalogs));
			 treeNodes.add(node);
		}
		
		return treeNodes;
	}
	
}
